package com.crm.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.crm.entity.User;

/**
 * Servlet Filter implementation class LoggingFilter
 */
public class LoggingFilter implements Filter {
	protected final Log logger = LogFactory.getLog(getClass());
    /**
     * Default constructor. 
     */
    public LoggingFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hreq = (HttpServletRequest) request;   
		HttpServletResponse hres = (HttpServletResponse) response;
		User user =(User)hreq.getSession().getAttribute("user");
		logger.info("url path "+hreq.getRequestURL());
		logger.info("Logged in user x0001 "+user);
		if(hreq.getRequestURL().indexOf("setpassword.do") >0 ){
			hres.sendRedirect(hreq.getContextPath()+"/jsp/setpassword.jsp?user="+hreq.getParameter("user"));
		}else if(hreq.getRequestURL().indexOf("setpass.do") >0 ){
			hres.sendRedirect(hreq.getContextPath()+"/jsp/index.jsp");
		}else if(hreq.getRequestURL().indexOf("forgetPass.do") >0 ){
			
			hres.sendRedirect(hreq.getContextPath()+"/jsp/index.jsp");
			
		}else  if(hreq.getRequestURL().indexOf("login.do") <0 && (user==null || user.getUserName().trim().length()<=0)){
			hres.sendRedirect(hreq.getContextPath()+"/jsp/index.jsp");
			return;
		}
/*	else if(hreq.getRequestURL().indexOf("Login.jsp?error=")>0 ){
		System.out.println("the index of:"+hreq.getRequestURL().indexOf("Login.jsp?error="));
		hres.sendRedirect(hreq.getContextPath()+"/jsp/Login.jsp?error="+"Mail Is Send to Your MailID");
		return;
	}*/
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		System.out.println("Initilzing logging....");
		LoggerUtil.setUpLog(LoggerUtil.LOGNAME);
		logger.info("Logging enabled");
		
	}

}
